import { connect } from 'umi';
import type { UserType } from '../../models/user';
import BaseModal from '@/components/BaseModal';
import { AntDesignOutlined } from '@ant-design/icons';
import { GridContent, ProFormText } from '@ant-design/pro-components';
import { Avatar, Button, Card, Col, Form, Row, Tag } from 'antd';
import { useRef, useState } from 'react';
import UserInfo from './form';
import { LockOutlined } from '@ant-design/icons';
import { baseFormConfig } from '@/components/BaseForm/config';
import { themeButtonStyle } from '../../../config/globalStyle';
import { ButtonStyle } from '../../../config/globalStyle';

import './style.less';

const fullHeight = {
  minHeight: '20vh',
};

const fullHeight2 = {
  minHeight: '40vh',
};

// !! 曾今的mock 不能删除 可能会影响到很多地方 方便后续修改
// 0: "管理员",
// 1: "老师"

// 1：管理员 2: 学生 3: 老师 4: 家长
const roleMap = {
  1: '管理员',
  2: '学生',
  3: '老师',
  4: '家长',
};

const UpdatePassword = (props: any) => {
  const { handleOpen, handleClose } = props;
  const formRef = useRef<any>(null);
  const onFinish = (values: any) => {
    console.log('Success:', values);
    formRef.current
      .validateFields()
      .then(() => {
        // 遍历所有表单项，判断是否填写完毕
        const hasError = Object.keys(formRef.current.getFieldsError()).some((field) => {
          return formRef.current.isFieldTouched(field) && formRef.current.getFieldError(field);
        });
        if (hasError) {
          // 表单验证失败，展示错误信息
        } else {
          // 表单验证成功，可以提交表单
          console.log('表单验证成功，可以提交表单');
          handleClose();
        }
      })
      .catch((error: any) => {
        // 表单验证失败，展示错误信息
        console.log(error);
      });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <Form
      {...baseFormConfig}
      ref={formRef}
      name="basic"
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item label="旧密码" name="oldpwd">
        <ProFormText.Password
          name="oldpwd"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '密码不少于8位, 并且必须包含两种字符',
            },
          ]}
        />
      </Form.Item>
      <Form.Item label="新密码" name="newpwd">
        <ProFormText.Password
          name="newpwd"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '密码不少于8位, 并且必须包含两种字符',
            },
          ]}
        />
      </Form.Item>
      <Form.Item label="确认密码" name="confirmpwd">
        <ProFormText.Password
          name="confirmpwd"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '密码不少于8位, 并且必须包含两种字符',
            },
          ]}
        />
      </Form.Item>
      <Form.Item>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
          }}
        >
          <Button key="cancel" onClick={handleClose} style={ButtonStyle}>
            取消
          </Button>
          <Button key="submit" type="primary" onClick={onFinish} style={ButtonStyle}>
            确认
          </Button>
        </div>
      </Form.Item>
    </Form>
  );
};

const PersonalCenter = ({
  name,
  role,
  info,
  dispatch,
}: {
  name: UserType['name'];
  role: UserType['role'];
  info: UserType['info'];
  dispatch: any;
}) => {
  console.log('info', info, role);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);

  const handleOpen = () => setIsModalOpen(true);
  const handleClose = () => setIsModalOpen(false);

  const handlePasswordOpen = () => setIsPasswordModalOpen(true);
  const handlePasswordClose = () => setIsPasswordModalOpen(false);

  const UpdatePasswordChildProps = {
    handleOpen: handlePasswordOpen,
    handleClose: handlePasswordClose,
  };
  const UpdatePasswordProps = {
    title: '修改密码',
    handleOpen: handlePasswordOpen,
    handleClose: handlePasswordClose,
    isModalOpen: isPasswordModalOpen,
    ModalChildren: () => <UpdatePassword {...UpdatePasswordChildProps} />,
    footer: false,
  };

  const userInfoProps = {
    handleClose,
    role,
  };
  /** 编辑信息配置 */
  const releaseProps = {
    title: '编辑信息',
    handleOpen,
    handleClose,
    isModalOpen,
    footer: false,
    ModalChildren: () => <UserInfo {...userInfoProps} />,
  };
  return (
    <GridContent>
      <Row gutter={24}>
        <Col lg={8} md={8} flex={1}>
          <Card style={fullHeight}>
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'column',
              }}
            >
              <Avatar
                // draggable={false}
                style={{ border: '1px solid black' }}
                src="https://joesch.moe/api/v1/random?key=1"
                size={{ xs: 24, sm: 80, md: 80, lg: 80, xl: 80, xxl: 80 }}
                icon={<AntDesignOutlined />}
              />
              <div className="userinfo">
                <p className="username"> {name}</p>
                <Tag
                  color="orange"
                  style={{
                    minWidth: '60px',
                    textAlign: 'center',
                    marginTop: '5px',
                    marginBottom: '5px',
                  }}
                >
                  {roleMap[role]}
                </Tag>
                <Button onClick={handlePasswordOpen} style={themeButtonStyle}>
                  修改密码
                </Button>
              </div>
            </div>
          </Card>
        </Col>
        <Col lg={16} md={16} span={24}>
          <Card style={fullHeight2} className="infoDetail">
            <Form
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 14 }}
              layout="horizontal"
              style={{ maxWidth: 1000 }}
            >
              <Form.Item>
                <Button
                  onClick={handleOpen}
                  style={{
                    ...themeButtonStyle,
                    // marginLeft: "30px",
                    marginBottom: '10px',
                  }}
                >
                  + 编辑信息
                </Button>
              </Form.Item>
              {role === 1 && (
                <>
                  <Form.Item label="学校名称：" name="disabled" valuePropName="checked">
                    {info.schoolName}
                  </Form.Item>
                  <Form.Item
                    label="学校简介："
                    name="disabled"
                    valuePropName="checked"
                    style={{
                      textAlign: 'justify',
                    }}
                  >
                    {info.schoolDetail}
                  </Form.Item>
                  <Form.Item label="学校地址：" name="disabled" valuePropName="checked">
                    {info.schoolAddress}
                  </Form.Item>
                  <Form.Item label="校长姓名：" name="disabled" valuePropName="checked">
                    {info.headmaster}
                  </Form.Item>
                </>
              )}
              {role === 3 && (
                <>
                  <Form.Item label="姓名：" name="disabled" valuePropName="checked">
                    {name}
                  </Form.Item>
                  <Form.Item
                    label="手机号："
                    name="disabled"
                    valuePropName="checked"
                    style={{
                      textAlign: 'justify',
                    }}
                  >
                    {info.phoneNumber}
                  </Form.Item>
                  <Form.Item label="所属学校：" name="disabled" valuePropName="checked">
                    {info.schoolName}
                  </Form.Item>
                  <Form.Item label="身份：" name="disabled" valuePropName="checked">
                    {info.identity}
                  </Form.Item>
                  <Form.Item label="学科：" name="disabled" valuePropName="checked">
                    {info.subject}
                  </Form.Item>
                </>
              )}
            </Form>
          </Card>
        </Col>
      </Row>
      <BaseModal {...releaseProps} />
      <BaseModal {...UpdatePasswordProps} />
    </GridContent>
  );
};

export default connect(({ user }: { user: UserType }) => ({
  name: user.name,
  role: user.role,
  info: user.info,
}))(PersonalCenter);
// export default PersonalCenter;
